package wx

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
)

type UserDetail struct {
	Openid   string `json:"openid"`
	Nickname string `json:"nickname"`
}

type WxTools struct {
	Appid       string // 小程序appid
	AppSecret   string // 小程序app_secret
	accessToken string // access_token
	expiresIn   int64  // 有效时间
}

func InitWx(appid string, AppSecret string) *WxTools {
	return &WxTools{
		Appid:     appid,
		AppSecret: AppSecret,
	}
}

func (w *WxTools) getAccessToken() (string, error) {
	if w.accessToken != "" && (w.expiresIn > 0 && w.expiresIn > 7000) {
		return w.accessToken, nil
	}
	postStr := fmt.Sprintf(`{"appid":"%s","secret":"%s","grant_type":"client_credential"}`, w.Appid, w.AppSecret)
	res, err := http.Post("https://api.weixin.qq.com/cgi-bin/token", "application/json", strings.NewReader(postStr))
	if err != nil {
		return "", err
	}
	defer res.Body.Close()
	var result struct {
		AccessToken string `json:"access_token"`
		ExpiresIn   int64  `json:"expires_in"`
	}
	resStr, err := io.ReadAll(res.Body)
	err = json.Unmarshal(resStr, &result)
	if err != nil {
		return "", err
	}
	w.expiresIn = result.ExpiresIn
	w.accessToken = result.AccessToken
	return result.AccessToken, nil
}

func (w *WxTools) Code2Session(code string) (openid string, sessionKey string) {
	res, err := http.Get(fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
		w.Appid, w.AppSecret, code))
	if err != nil {
		fmt.Println(err.Error())
		return "", ""
	}
	defer res.Body.Close()

	var result struct {
		SessionKey string `json:"session_key"`
		Openid     string `json:"openid"`
	}

	resStr, err := io.ReadAll(res.Body)
	err = json.Unmarshal(resStr, &result)
	if err != nil {
		fmt.Println(err.Error())
		return "", ""
	}

	return result.Openid, result.SessionKey
}
